package com.rgs.module.file.controller;

import cn.hutool.core.img.ImgUtil;
import com.google.common.io.Files;
import com.rgs.base.core.file.storage.FileStorageService;
import com.rgs.base.core.model.WebApiReturnResultModel;
import com.rgs.module.file.bo.FileBriefInfoBO;
import com.rgs.module.file.entity.FileInfoDO;
import com.rgs.module.file.enums.FileInfoStatusEnum;
import com.rgs.module.file.filter.FileInfoFilterDTO;
import com.rgs.module.file.service.FileInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;

/**
 * @author Ren Gaoshuai
 * @ClassName FileController
 * @Description 上传文件
 * @date 2022-01-26 9:08
 **/
@RestController
@RequestMapping("/v1/file")
@Api(tags = "文件相关服务")
public class FileController {

    @Resource
    FileStorageService fileStorageService;
    @Resource
    FileInfoService fileInfoService;

    @PostMapping("/fileUpload")
    @ApiOperation(value = "文件上传", consumes = "multipart/form-data")
    public WebApiReturnResultModel<FileBriefInfoBO> fileUpload(
            @ApiParam(value = "文件流输入对象", required = true)
            @RequestParam(name = "multipartFile") MultipartFile multipartFile,
            @ApiParam(value = "是否压缩图片0不压缩，1压缩，默认0", required = false, example = "0")
            @RequestParam(name = "isImageCompress", defaultValue = "0") Integer isImageCompress) throws IOException {
        //文件信息保存到本地数据库
        String suffix = Files.getFileExtension(multipartFile.getOriginalFilename())
                .replace(".", "");
        //生成一个UUID.后缀
        String fileId = fileStorageService.generateFileName(suffix);
        Long size = multipartFile.getSize();
        InputStream inputStream = multipartFile.getInputStream();
        //文件流保存到文件服务器，返回一个uuid
        FileInfoDO fileInfoDO = FileInfoDO.builder()
                .fileName(fileId)
                .createTime(LocalDateTime.now())
                .status(FileInfoStatusEnum.UPLOADING.getCode())
                .crc32(0L)
                .size(size).build();
        fileInfoService.insert(fileInfoDO);
        if (isImageCompress == 0) {
            //直接保存到文件服务器
            fileStorageService.saveForInputStream(inputStream, fileId);
        } else {
            //缩放图片
            BufferedImage srcImage = ImageIO.read(inputStream);
            Image scale = ImgUtil.scale(srcImage, 800, 800);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImgUtil.write(scale, suffix, os);
            //保存到文件服务器
            fileStorageService.saveForByte(os.toByteArray(), fileId);
        }
        //更改数据库的文件状态
        fileInfoService.updateSelectiveByFilter(
                FileInfoDO.builder()
                        .status(FileInfoStatusEnum.NORMAL.getCode())
                        .build()
                , FileInfoFilterDTO.builder()
                        .fileName(fileId)
                        .build());
        return WebApiReturnResultModel.ofSuccess(FileBriefInfoBO.builder()
                .fileName(fileId)
                .url(fileStorageService.fileUrl(fileId))
                .fileSize(size)
                .build()
        );
    }
}
